/**
 * 打印访问日志中间件
 */
import { ssrMiddleware } from 'quasar/wrappers'
import jwt from 'jsonwebtoken';
import moment from 'moment';

// "async" is optional;
// more info on params: https://v2.quasar.dev/quasar-cli/developing-ssr/ssr-middlewares
export default ssrMiddleware(async ({ app /*, resolveUrlPath, publicPath, render */ }) => {
  // something to do with the server "app"
  app.use(require('morgan')(function (tokens, req, res) {
    let ip = (req.ip || '').match(/\d+\.\d+\.\d+\.\d+/);
    if (ip && ip.length > 0) {
      ip = ip[0];
    } else {
      ip = '';
    }

    const token = req.get('Authorization') ? req.get('Authorization').split(' ') : [];
    let id = '', nickname = '', tid = '';
    if (token.length >= 2) {
      try {
        const decoded = jwt.verify(token[1], global.privateKey);
        tid = decoded.tid;
        id = decoded.id;
        nickname = decoded.nickname;
      } catch (e) {
        console.log(e);
      }
    }

    return [
      moment().format('YYYY/MM/DD HH:mm:ss'),
      `tenant_id:${tid}`,
      `user:${nickname}(${id})`,
      'from:', ip,
      '||', req.get('x-forwarded-for') || '', '-',
      tokens.method(req, res),
      tokens.url(req, res),
      'status:', tokens.status(req, res),
      'content-length', tokens.res(req, res, 'content-length'), '-> request took:',
      tokens['response-time'](req, res), 'ms'
    ].join(' ');
  }));
});
